<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
      <el-form-item label="样本源名称/编号" prop="sourceId">
        <el-select
          v-model="queryParams.sourceId"
          :loading="sourceLoading"
          :remote-method="getSource"
          clearable
          filterable
          placeholder="请输入样本源名称或编号"
          remote
        >
          <el-option
            v-for="item in sourceList"
            :key="item.sourceId"
            :label="item.label"
            :value="item.sourceId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划随访时间" prop="followPlanRange">
        <el-date-picker
          v-model="queryParams.followPlanRange"
          :picker-options="pickerOptions"
          align="right"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="随访状态" prop="followState">
        <el-select
          v-model="queryParams.followState"
          clearable
          placeholder="随访状态"
          size="small"
          style="width: 214px"
        >
          <el-option
            v-for="dict in followStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="随访方式" prop="followWay">
        <el-select
          v-model="queryParams.followWay"
          clearable
          placeholder="随访状态"
          size="small"
          style="width: 214px"
        >
          <el-option
            v-for="dict in followWayOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增随访
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:edit']"
          :disabled="multiple"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="batchRecovery"
        >批量恢复随访
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:edit']"
          :disabled="multiple"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="batchRelapsed"
        >批量添加到已复发
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:edit']"
          :disabled="multiple"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="batchTerminated"
        >批量添加到已终止
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:edit']"
          :disabled="multiple"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="batchLostUp"
        >批量添加到已失访
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="followList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column v-if="false" align="center" label="随访ID" prop="followId"/>
      <el-table-column align="center" label="样本源编号" prop="sourceCode"/>
      <el-table-column align="center" label="样本源名称" prop="sourceName"/>
      <el-table-column align="center" label="计划随访时间" prop="followPlan" width="180">
        <template slot-scope="scope">
          <span v-show="!scope.row.editShow">{{ parseTime(scope.row.followPlan, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <el-date-picker v-show="scope.row.editShow"
                          v-model="scope.row.followPlan"
                          :clearable="false"
                          placeholder="计划随访时间"
                          size="small"
                          style="width: 100%"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="实际随访时间" prop="followFact" width="180">
        <template slot-scope="scope">
          <span v-show="!scope.row.editShow">{{ parseTime(scope.row.followFact, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <el-date-picker v-show="scope.row.editShow"
                          v-model="scope.row.followFact"
                          :clearable="false"
                          placeholder="实际随访时间"
                          size="small"
                          style="width: 100%"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="随访状态" prop="followState">
        <template slot-scope="scope">
          <span v-show="!scope.row.editShow">{{ followStateFormat(scope.row) }}</span>
          <el-select
            v-show="scope.row.editShow"
            v-model="scope.row.followState"
            :clearable="false"
            placeholder="随访状态"
            size="small"
            style="width: 150px"
          >
            <el-option
              v-for="dict in followStateOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column align="center" label="随访方式" prop="followWay">
        <template slot-scope="scope">
          <span v-show="!scope.row.editShow">{{ followWayFormat(scope.row) }}</span>
          <el-select
            v-show="scope.row.editShow"
            v-model="scope.row.followWay"
            :clearable="false"
            placeholder="随访方式"
            size="small"
            style="width: 150px"
          >
            <el-option
              v-for="dict in followWayOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" align="center" label="随访描述" prop="followDesc">
        <template slot-scope="scope">
          <el-input v-show="scope.row.editShow" v-model="scope.row.followDesc" placeholder="随访描述" size="small"
          ></el-input>
          <span v-show="!scope.row.editShow">{{ scope.row.followDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="参与随访人员" prop="followVisitor">
        <template slot-scope="scope">
          <el-input v-show="scope.row.editShow" v-model="scope.row.followVisitor" placeholder="参与随访人员" size="small"
          ></el-input>
          <span v-show="!scope.row.editShow">{{ scope.row.followVisitor }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="240px">
        <template slot-scope="scope">
          <div v-show="!scope.row.editShow">
            <el-button v-hasPermi="['research:follow:query']" icon="el-icon-view" size="mini" type="text"
                       @click="handleView(scope.row)"
            >查看
            </el-button>
            <el-button v-hasPermi="['research:follow:edit']" icon="el-icon-edit" size="mini" type="text"
                       @click="handleUpdate(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button v-hasPermi="['research:follow:edit']" icon="el-icon-edit" size="mini" type="text"
                       @click="handleQuestion(scope.row)"
            >问卷
            </el-button>
            <el-button v-hasPermi="['research:follow:remove']" icon="el-icon-delete" size="mini" type="text"
                       @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </div>
          <div v-show="scope.row.editShow">
            <el-button icon="el-icon-close" size="mini" type="text" @click="handleCancel(scope.$index, scope.row)">取消
            </el-button>
            <el-button icon="el-icon-check" size="mini" type="text" @click="handleSave(scope.$index, scope.row)">保存
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加随访对话框 -->
    <el-dialog :visible.sync="addOpen" append-to-body title="添加随访" width="700px">
      <el-form ref="form" :model="form" :rules="addRules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本源名称/编号" prop="sourceId" size="small" style="width: 100%">
              <el-select
                v-model="form.sourceId"
                :loading="sourceLoading"
                :remote-method="getSource"
                clearable
                filterable
                placeholder="请输入样本源名称或编号"
                remote
              >
                <el-option
                  v-for="item in sourceList"
                  :key="item.sourceId"
                  :label="item.label"
                  :value="item.sourceId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="问卷表单" prop="formKey">
              <el-select
                v-model="form.formKey"
                clearable
                placeholder="问卷表单"
                size="small"
              >
                <el-option
                  v-for="dict in customForms"
                  :key="dict.formKey"
                  :label="dict.formName"
                  :value="dict.formKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="随访状态" prop="followState">
              <el-select
                v-model="form.followState"
                clearable
                placeholder="随访状态"
                size="small"
              >
                <el-option
                  v-for="dict in followStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访方式" prop="followWay">
              <el-select
                v-model="form.followWay"
                clearable
                placeholder="随访状态"
                size="small"
              >
                <el-option
                  v-for="dict in followWayOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="参与随访人员">
          <el-tag
            v-for="visitor in visitors"
            :key="visitor"
            :disable-transitions="false"
            closable
            @close="handleVisitorClose(visitor)"
          >
            {{ visitor }}
          </el-tag>
          <el-input
            v-if="visitorVisible"
            ref="saveVisitorInput"
            v-model="visitorValue"
            class="input-new-tag"
            size="small"
            @blur="handleVisitorConfirm"
            @keyup.enter.native="handleVisitorConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showVisitor">+ 随访人员</el-button>
        </el-form-item>
        <el-form-item label="随访描述" prop="followDesc">
          <el-input v-model="form.followDesc" :rows="2" placeholder="请输入随访描述" type="textarea"/>
        </el-form-item>
        <el-form-item label="随访方案">
          <el-tabs :active-name="activeTab">
            <el-tab-pane label="单次随访" name="one">
              <el-form-item label="计划随访时间" prop="followPlan">
                <el-date-picker v-model="form.followPlan" clearable
                                placeholder="选择计划随访时间"
                                size="small"
                                style="width: 300px"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="模板随访" name="temp">
              <el-form-item label="首次随访时间" prop="followPlan">
                <el-date-picker v-model="form.followPlan" clearable
                                placeholder="选择计划随访时间"
                                size="small"
                                style="width: 300px"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="随访模板" prop="followTempId">
                <el-select
                  v-model="form.followTempId"
                  clearable
                  placeholder="随访模板"
                  size="small"
                  style="width: 300px"
                >
                  <el-option
                    v-for="dict in followTempList"
                    :key="dict.followTempId"
                    :label="dict.followTempName"
                    :value="dict.followTempId"
                  />
                </el-select>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="规律性随访" name="law">
              <el-form-item label="首次随访时间" prop="followPlan">
                <el-date-picker v-model="form.followPlan" clearable
                                placeholder="选择计划随访时间"
                                size="small"
                                style="width: 300px"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="间隔时间" prop="intervalTime">
                <el-input-number v-model="form.intervalTime" controls-position="right" style="width: 100px"
                ></el-input-number>
                <el-select v-model="form.intervalUnit" placeholder="请选择时间单位" style="width: 200px">
                  <el-option
                    v-for="item in timeType"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="随访次数" prop="followCount" style="margin-top: 10px">
                <el-input-number v-model="form.followCount" controls-position="right" style="width: 300px"
                ></el-input-number>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看或修改随访对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="700px">
      <el-form ref="form" :disabled="disabled" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本源名称/编号" prop="sourceId">
              <el-input v-model="form.sourceName" :disabled="true" placeholder="样本源名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="问卷表单" prop="formKey">
              <el-select
                v-model="form.formKey"
                clearable
                placeholder="问卷表单"
                size="small"
                style="width: 214px"
              >
                <el-option
                  v-for="dict in customForms"
                  :key="dict.formKey"
                  :label="dict.formName"
                  :value="dict.formKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="随访状态" prop="followState">
              <el-select
                v-model="form.followState"
                clearable
                placeholder="随访状态"
                size="small"
                style="width: 214px"
              >
                <el-option
                  v-for="dict in followStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访方式" prop="followWay">
              <el-select
                v-model="form.followWay"
                clearable
                placeholder="随访状态"
                size="small"
                style="width: 214px"
              >
                <el-option
                  v-for="dict in followWayOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="参与随访人员">
          <el-tag
            v-for="visitor in visitors"
            :key="visitor"
            :closable="!disabled"
            :disable-transitions="false"
            @close="handleVisitorClose(visitor)"
          >
            {{ visitor }}
          </el-tag>
          <el-input
            v-if="visitorVisible"
            ref="saveVisitorInput"
            v-model="visitorValue"
            class="input-new-tag"
            size="small"
            @blur="handleVisitorConfirm"
            @keyup.enter.native="handleVisitorConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showVisitor">+ 随访人员</el-button>
        </el-form-item>
        <el-form-item label="随访描述" prop="followDesc">
          <el-input v-model="form.followDesc" :rows="2" placeholder="请输入随访描述" type="textarea"/>
        </el-form-item>

        <el-divider><i class="el-icon-s-promotion"></i></el-divider>
        <div
          v-for="(domain, index) in form.formJson"
          :key="index"
          :label="domain.controlLable"
        >
          <parser ref="formCustom" :form-conf="domain.json"/>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addFollow, delFollow, getFollow, listFollow, updateFollow, updateFollowBatch } from '@/api/research/follow'
import { getSourceByCodeOrName } from '@/api/biobank/source'
import { allForm, formJsonShow } from '@/api/tool/form'
import { listFollowTemp } from '@/api/research/followTemp'
import Parser from 'form-gen-parser'

export default {
  name: 'Follow',
  components: {
    Parser
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      sourceLoading: false,
      // 选中数组
      ids: [],
      // 选中数组
      selectFollows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 添加随访人员 input visible
      visitorVisible: false,
      // 添加随访人员 input value
      visitorValue: '',
      // 随访方案
      activeTab: 'one',
      // 随访人员数组
      visitors: [],
      // 随访列表表格数据
      followList: [],
      // 查询的样本列表
      sourceList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 添加随访弹出层
      addOpen: false,
      // 是否可编辑
      disabled: false,
      // 随访状态
      followStateOptions: [],
      // 随访方式
      followWayOptions: [],
      // 问卷表单
      customForms: [],
      // 随访模板
      followTempList: [],
      // 时间单位
      timeType: [
        { key: 'h', value: '时' },
        { key: 'd', value: '天' },
        { key: 'w', value: '周' },
        { key: 'm', value: '月' },
        { key: 'y', value: '年' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sourceId: undefined,
        followPlanRange: undefined,
        followState: undefined,
        followWay: undefined
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 表单参数
      form: {},
      // 编辑表单校验
      rules: {},
      // 添加随访表单校验
      addRules: {
        sourceId: { required: true, trigger: 'change', message: '样本源不能为空' },
        followState: { required: true, trigger: 'change', message: '随访状态不能为空' },
        followWay: { required: true, trigger: 'change', message: '随访方式不能为空' },
        followDesc: { max: 30, trigger: 'blur', message: '随访描述不能超过30个字符' }
      }
    }
  },
  created() {
    this.getDicts('follow_state').then(response => {
      this.followStateOptions = response.data
    })
    this.getDicts('follow_way_type').then(response => {
      this.followWayOptions = response.data
    })
    this.getList()
    this.getCustomForm()
    this.getFollowTemp()
  },
  methods: {
    /** 查询随访列表列表 */
    getList() {
      this.loading = true
      listFollow(this.queryParams).then(response => {
        this.followList = response.rows
        this.followList.map(item => {
          if(item.editShow){
            item.editShow = false
          }
        })
        this.total = response.total
      }).finally(() => { this.loading=false })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.addOpen = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.followId)
      this.selectFollows = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.addOpen = true
      this.title = '添加随访'
    },
    // 查看按钮点击事件
    handleView(row) {
      this.reset()
      getFollow(row.followId).then(response => {
        this.form = response.data
        this.visitors = this.form.followVisitor.split(',')
        this.disabled = true
        this.open = true
        this.title = '查看随访'
        this.showFormJson(this.form.formKey)
      })
    },
    /** 编辑按钮操作 */
    handleUpdate(index, row) {
      row.editShow = true
      this.$set(this.followList, index, row)
    },
    // 问卷按钮点击事件
    handleQuestion(row) {
      this.reset()
      getFollow(row.followId).then(response => {
        this.form = response.data
        this.visitors = this.form.followVisitor.split(',')
        this.disabled = false
        this.open = true
        this.title = '编辑随访问卷'
        this.showFormJson(this.form.formKey)
      })
    },
    // 取消按钮点击事件
    handleCancel(index, row) {
      row.editShow = false
      this.$set(this.followList, index, row)
    },
    // 保存按钮点击事件
    handleSave(index, row) {
      updateFollow(row).then(res => {
        this.$message.success('保存成功')
        row.editShow = false
        this.$set(this.followList, index, row)
      })
    },
    // 批量恢复随访
    batchRecovery() {
      this.batchHandle(this.GLOBAL.FOLLOW_STATE.TODO)
    },
    // 批量添加到已复发
    batchRelapsed() {
      this.batchHandle(this.GLOBAL.FOLLOW_STATE.RECUR)
    },
    // 批量添加到已终止
    batchTerminated() {
      this.batchHandle(this.GLOBAL.FOLLOW_STATE.STOP)
    },
    // 批量添加到已失访
    batchLostUp() {
      this.batchHandle(this.GLOBAL.FOLLOW_STATE.LOST)
    },
    batchHandle(state) {
      let follows = this.selectFollows.map(item => {
        item.followState = state
        return item
      })
      updateFollowBatch(follows).then(res => {
        this.getList()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.form.followVisitor = this.visitors.join(',')
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.followId != null) {
            if (this.form.formKey !== '' && this.form.formKey !== null && this.form.formKey !== undefined) {
              let custFormRef = this.$refs.formCustom[0]
              let custForm = custFormRef.$refs[custFormRef.formConf.formRef]
              let custData = custFormRef[custFormRef.formConf.formModel]
              let custDesc = {}
              for (let onceForm of this.form.formJson) {
                for (let onceField of onceForm.json.fields) {
                  if (onceField.__vModel__) {
                    custDesc[onceField.__vModel__] = onceField.__config__.label
                  } else {
                    if (onceField.__config__ && onceField.__config__.children && onceField.__config__.children.length > 0) {
                      onceField.__config__.children.forEach(child => {
                        custDesc[child.__vModel__] = child.__config__.label
                      })
                    }
                  }
                }
              }
              custForm.validate(e => {
                if (e) {
                  this.form.formData = JSON.stringify(custData)
                  this.form.formDesc = JSON.stringify(custDesc)
                }
              })
            }
            updateFollow(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addFollow(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.addOpen = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const followIds = row.followId || this.ids
      this.$confirm('是否确认删除随访列表编号为"' + followIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delFollow(followIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    // 获取随访模板
    getFollowTemp() {
      listFollowTemp().then(response => {
        this.followTempList = response.data
      })
    },
    // 渲染动态表单
    showFormJson(formKey) {
      if (!formKey || formKey === '') {
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.form, 'formJson', formJson)
        this.disableForm(this.form.formJson[0].json)
        if (this.form.formData != undefined) {
          this.fillFormData(this.form.formJson[0].json, JSON.parse(this.form.formData))
          this.$set(this.form, 'formJson', formJson)
        }
      })
    },
    // 动态表单值回写
    fillFormData(form, data) {
      form.fields.map(item => {
        if (item.__vModel__) {
          const val = data[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              const childVal = data[child.__vModel__]
              if (childVal) {
                child.__config__.defaultValue = childVal
              }
            })
            return item
          }
        }
      })
    },
    // 设置动态表单禁用状态
    disableForm(form) {
      form.fields.map(item => {
        if (item.__vModel__) {
          item.disabled = this.disabled
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              child.disabled = this.disabled
            })
            return item
          }
        }
      })
    },
    // -- 添加随访人员 -- start
    handleVisitorClose(visitor) {
      this.visitors.splice(this.visitors.indexOf(visitor), 1)
    },
    showVisitor() {
      this.visitorVisible = true
      this.$nextTick(_ => {
        this.$refs.saveVisitorInput.$refs.input.focus()
      })
    },
    handleVisitorConfirm() {
      let inputValue = this.visitorValue
      if (inputValue) {
        if (inputValue.length >= 10) {
          this.$message.error('随访人员姓名不能超过10个字符')
          this.visitorValue = ''
          return false
        }
        this.visitors.push(inputValue)
      }
      this.visitorVisible = false
      this.visitorValue = ''
    },
    // -- 添加随访人员 -- end
    // 获取所有问卷表单
    getCustomForm() {
      let queryForm = {}
      queryForm.formType = 'question'
      allForm(queryForm).then(response => {
        this.customForms = response.data
      })
    },
    // 根据样本名称查询
    getSource(sourceName) {
      if (sourceName !== '') {
        this.sourceLoading = true
        getSourceByCodeOrName(sourceName).then(res => {
          this.sourceLoading = false
          this.sourceList = res.data
          if (this.sourceList.length > 0) {
            this.sourceList.map(item => {
              return item.label = item.sourceCode + '-' + item.sourceName + '-' + item.sourceTypeName
            })
          }
        })
      }
    },
    // 随访状态字典翻译
    followStateFormat(row, column) {
      return this.selectDictLabel(this.followStateOptions, row.followState)
    },
    // 随访方式字典翻译
    followWayFormat(row, column) {
      return this.selectDictLabel(this.followWayOptions, row.followWay)
    },
    // 表单重置
    reset() {
      this.form = {
        followId: undefined,
        sourceId: undefined,
        followPlan: undefined,
        followFact: undefined,
        followNum: undefined,
        followVisitor: undefined,
        followDesc: undefined,
        followState: undefined,
        followWay: undefined,
        formKey: undefined,
        formData: undefined,
        formDesc: undefined,
        followTempId: undefined,
        intervalTime: undefined,
        intervalUnit: undefined,
        followCount: undefined
      }
      this.resetForm('form')
      this.visitors = []
      this.activeTab = 'one'
    }
  }
}
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 7px;
}

.button-new-tag {
  margin-left: 7px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 7px;
  vertical-align: bottom;
}
</style>
